package com.efounder.chat.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.MobileShareFirstAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.ShareBean;
import com.efounder.chat.model.ShareContent;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.ChatTypeUtil;
import com.efounder.chat.utils.HandleShareIntentUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.widget.ChatTextView;
import com.efounder.chat.widget.ShareEnterDialog;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ActivityUtils;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 联信应用本地分享activity
 *
 * @author yqs
 */

public class MobileShareActivity extends BaseActivity {

    private ChatTextView testTextView;
    private RecyclerView recyclerView;
    //将要发送的消息
    private IMStruct002 preSendIMStruct002;

    private List<IMStruct002> messageList;
    //分享类型 0 文字 1 图片 2 图文消息  图片文字带url
    private int shareType = 0;
    private MobileShareFirstAdapter mAdapter;
    private List<ShareBean> dataList;
    private List<ShareBean> topList;
    private ArrayList<String> localPathList;
    private static final int SELECT_FRIEND = 88;
    private static final int SELECT_GROUP = 90;
    private static final int SELECT_ZONE = 92;

    private ShareContent shareContent;

    //如果包含这个sendImStruct002，则直接发送imstrct002,不需要处理分享信息
    private boolean sendImStruct002 = false;
    private IMStruct002 imStruct002;

    //分享消息的说明
    private String shareExplain = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_mobile_share);
        initView();
        checkIsLogin();


    }

    private void checkIsLogin() {
        String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        if (null == chatUserID || "".equals(chatUserID)
                || null == chatPassword || "".equals(chatPassword)) {
            //用户没有登陆 跳转登录界面
            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                    .setMessage(ResStringUtil.getString(R.string.chat_not_login_after_share))
                    .setCancelable(false)
                    .setPositiveButton(R.string.chat_go_login, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            try {
                                intent.setClass(MobileShareActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
                                startActivity(intent);
                                finish();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .setNeutralButton(R.string.common_text_back, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();


            return;
        } else {
            initData();
        }

    }


    private void initView() {
        //标题
        TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_share);
        TextView cannelView = (TextView) findViewById(R.id.tv_save);
        cannelView.setVisibility(View.VISIBLE);
        cannelView.setText(R.string.common_text_cancel);
        cannelView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        testTextView = (ChatTextView) findViewById(R.id.textview);
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initData() {
        messageList = new ArrayList<>();
        Intent intent = getIntent();
        if (intent.hasExtra("sendImStruct002")) {
            //直接分享消息
            sendImStruct002 = true;
            imStruct002 = (IMStruct002) intent.getExtras().get("imStruct002");
        } else {
            shareContent = HandleShareIntentUtil.handleIntent(this, intent);
            if (shareContent != null) {
                shareType = shareContent.getType();
                if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_TEXT ||
                        shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_WEB) {
                    testTextView.setText(shareContent.getText());
                    createTextMessage();
                } else if (shareContent.getType() == HandleShareIntentUtil.SHARE_TYPE_IMAGE) {

                    localPathList = shareContent.getPictureList();
                }
            }
        }

        if (getIntent().hasExtra("shareExplain")) {
            shareExplain = getIntent().getStringExtra("shareExplain");
        }

        dataList = new ArrayList<>();
        topList = new ArrayList<>();

        initShowListData();

        mAdapter = new MobileShareFirstAdapter(this, dataList);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnitemClickListener(new MobileShareFirstAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int posotion, ShareBean shareBean) {
                clickItem(posotion, shareBean);
            }
        });

    }


    private void clickItem(int position, ShareBean shareBean) {
        if (shareBean.getType().equals(ShareBean.SHARE_TYPE_SELECT_FRIEND)) {
            //ToastUtil.showToast(this, "选择好友");
            Intent intent = new Intent(this, SelectFriendActivity.class);
            intent.putExtra("isSingleMode", true);
            startActivityForResult(intent, SELECT_FRIEND);
        } else if (shareBean.getType().equals(ShareBean.SHARE_TYPE_SELECT_GROUP)) {
            //ToastUtil.showToast(this, "选择群聊");
            Intent intent = new Intent(this, SelectGroupActivity.class);
            startActivityForResult(intent, SELECT_GROUP);
        }
        /*else if (shareBean.getType().equals(ShareBean.SHARE_TYPE_ZONE)) {
            String className = getResources().getString(R.string.from_group_backto_first);
            IMStruct002 good = (IMStruct002) getIntent().getExtras().get("imStruct002");
            String goodUrl = getIntent().getStringExtra("goodUrl");


 //               startActivityForResult(intent, SELECT_ZONE);


        }*/
        else if (shareBean.getType().equals(ShareBean.SHARE_TYPE_CHAT)) {
            //ToastUtil.showToast(this, "分享到" + shareBean.getChatId());
            sendMessage(shareBean.getChatId(), shareBean.getChatType());
        }
    }

    /**
     * 发送消息
     *
     * @param chatId 接收人id
     * @param type   接收人类型 群聊或者单聊
     */
    private void sendMessage(final int chatId, final int type) {
        String name = "";
        if (type == StructFactory.TO_USER_TYPE_PERSONAL) {
            name =  WeChatDBManager.getInstance().getOneUserById(chatId).getReMark();
        } else {
            name =  WeChatDBManager.getInstance().getGroup(chatId, false).getGroupName();
        }


        final ShareEnterDialog dialog = new ShareEnterDialog(this, new ShareEnterDialog.OnEnterClick() {
            @Override
            public void buttonClick(boolean isSend) {
                if (isSend) {
                    if (sendImStruct002) {
                        preSendIMStruct002 = new IMStruct002();
                        preSendIMStruct002.setMessage(imStruct002.getMessage());
                        preSendIMStruct002.setMessageChildType(imStruct002.getMessageChildType());
                    }
                    if (preSendIMStruct002 != null) {
                        preSendIMStruct002.setToUserId(chatId);
                        preSendIMStruct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getUserID()));
                        preSendIMStruct002.setToUserType((byte) type);
                        preSendIMStruct002.setTime(System.currentTimeMillis());
                    }

                    //图片消息赋值
                    for (int i = 0; i < messageList.size(); i++) {
                        messageList.get(i).setToUserId(chatId);
                        messageList.get(i).setFromUserId(Integer.parseInt(EnvironmentVariable.getUserID()));
                        messageList.get(i).setToUserType((byte) type);
                        messageList.get(i).setTime(System.currentTimeMillis());
                    }

                    if (localPathList != null && localPathList.size() > 0) {
                        LoadingDataUtilBlack.show(MobileShareActivity.this, ResStringUtil.getString(R.string.chat_shareing));
                        Intent intent = new Intent();
                        intent.putExtra("id", chatId);
                        intent.putExtra("chattype", (byte) type);
                        intent.putExtra("share", "1");
                        intent.putExtra("shareImages", localPathList);
                        ChatActivitySkipUtil.startChatActivity(MobileShareActivity.this, intent);
                        LoadingDataUtilBlack.dismiss();
                        finish();
                    } else if (preSendIMStruct002 != null) {
                        LoadingDataUtilBlack.show(MobileShareActivity.this, ResStringUtil.getString(R.string.chat_shareing));
                        if (preSendIMStruct002 != null) {
                            JFMessageManager.getInstance().sendMessage(preSendIMStruct002);

                            LoadingDataUtilBlack.dismiss();
                            if (sendImStruct002) {
                                Intent intent = new Intent();
                                intent.putExtra("id", chatId);
                                intent.putExtra("chattype", (byte) type);
                                ChatActivitySkipUtil.startChatActivity(MobileShareActivity.this, intent);
                                finish();
                            } else {
                                showAlertDialog(true, ResStringUtil.getString(R.string.chat_share_success), (byte) type, chatId);
                            }


                            //ToastUtil.showToast(MobileShareActivity.this, "分享成功");
                        }


                    }
                } else {
                }
            }
        });
        dialog.setTitle(ResStringUtil.getString(R.string.chat_send_to) + name);
        if (sendImStruct002) {
            //组织分享的消息
            IMStruct002 preSendIMStruct002 = new IMStruct002();
            preSendIMStruct002.setMessage(imStruct002.getMessage());
            preSendIMStruct002.setMessageChildType(imStruct002.getMessageChildType());
            preSendIMStruct002.setToUserId(chatId);
            preSendIMStruct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getUserID()));
            preSendIMStruct002.setToUserType((byte) type);
            preSendIMStruct002.setTime(System.currentTimeMillis());

            dialog.setContent(shareExplain.equals("") ?
                    ChatTypeUtil.getMessageByType(this, preSendIMStruct002, "") : shareExplain);
        } else {
            dialog.setContent(shareContent.getText());
        }
        dialog.show();
    }


    private void initShowListData() {
        dataList = new ArrayList<>();
        topList = new ArrayList<>();
        ShareBean bean1 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_choose_friend)).type(ShareBean.SHARE_TYPE_SELECT_FRIEND).build();
        ShareBean bean2 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_choose) + getString(R.string.chat_room_name))
                .type(ShareBean.SHARE_TYPE_SELECT_GROUP).build();
//        ShareBean bean3 = new ShareBean.Builder().name("分享到引力场")
//                .type(ShareBean.SHARE_TYPE_ZONE).build();

        ShareBean bean4 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_lately)).type(ShareBean.SHARE_TYPE_RECENT).build();
        topList.add(bean1);
        topList.add(bean2);
//        topList.add(bean3);
        topList.add(bean4);
        dataList.addAll(topList);

        // List<ChatListItem> lists = WeChatDBManager.getInstance().getAllChatList();
        List<ChatListItem> lists = SystemInfoService.CHATITEMLIST;
        if (lists != null) {
            for (int i = 0; i < lists.size(); i++) {
                ChatListItem item = lists.get(i);
                ShareBean bean = null;
//                if (item.getChatType() == StructFactory.TO_USER_TYPE_GROUP){
//
//                }
                bean = new ShareBean.Builder().type(ShareBean.SHARE_TYPE_CHAT).name(item.getName())
                        .chatId(item.getUserId()).chatType(item.getChatType()).icon(item.getAvatar()).build();
                dataList.add(bean);

            }

        }


    }

    /**
     * 创建文字消息
     */
    private void createTextMessage() {
        if (shareType == HandleShareIntentUtil.SHARE_TYPE_TEXT) {
            preSendIMStruct002 = StructFactory.getInstance().createTextStruct(shareContent.getText(), StructFactory.TO_USER_TYPE_PERSONAL);
        } else if (shareType == HandleShareIntentUtil.SHARE_TYPE_WEB) {
            preSendIMStruct002 = StructFactory.getInstance().createShareWebStruct(shareContent.getUrl(),
                    shareContent.getImgUrl(), shareContent.getSubject(), shareContent.getText(), StructFactory.TO_USER_TYPE_PERSONAL);
        }
    }

    /**
     * 创建图片消息
     *
     * @param path
     */
    private void createImageMessage(String path) {
        shareType = 1;
        String scale = ImageUtil.getPicScale(path);
        IMStruct002 message = StructFactory.getInstance().createImageStruct("%s", path, scale, StructFactory.TO_USER_TYPE_PERSONAL);
        messageList.add(message);
    }

    /**
     * 创建图文消息
     *
     * @param
     */
    private void createImageAndTextMessage(String imagePath, String webUrl, String text) {
        shareType = 2;
        String scale = ImageUtil.getPicScale(imagePath);
        //  preSendIMStruct002 = StructFactory.getInstance().createImageStruct("%s", path, scale, StructFactory.TO_USER_TYPE_PERSONAL);
    }

    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && (requestCode == SELECT_GROUP || requestCode == SELECT_FRIEND)) {
            if (data != null && data.hasExtra("userId")) {
                //选择好友
                sendMessage(data.getIntExtra("userId", 0), StructFactory.TO_USER_TYPE_PERSONAL);
            } else {
                //选择群组
                if (data != null && data.hasExtra("groupId")) {
                    sendMessage(data.getIntExtra("groupId", 0), StructFactory.TO_USER_TYPE_GROUP);
                }
            }
        }
    }

    /**
     * @param success  是否分享成功
     * @param message  信息
     * @param chatType 聊天类型
     */
    public void showAlertDialog(final boolean success, String message, final byte chatType, final int chatId) {
        AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                .setMessage(message)
                .setCancelable(false)
                .setNegativeButton(R.string.common_text_back, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
//                        if (success) {
//                            finish();
//                        } else {
//                            dialog.dismiss();
//                        }

                    }
                }).create();
        if (success) {
            dialog.setButton(AlertDialog.BUTTON_POSITIVE, ResStringUtil.getString(R.string.chat_stay_in) + getString(R.string.app_name), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.putExtra("id", chatId);
                    intent.putExtra("chattype", chatType);
                    intent.putExtra("share", "1");
                    ChatActivitySkipUtil.startChatActivity(MobileShareActivity.this, intent);
                    finish();

                }
            });
            dialog.show();
        }

    }
        //分享消息的跳转入口
    public static void start(boolean b, IMStruct002 good, String shareExplain) {
        Intent intent =new Intent(ActivityUtils.getTopActivity(),MobileShareActivity.class);
        //是否是分享消息
        intent.putExtra("sendImStruct002",b);
        //消息
        intent.putExtra("imStruct002",good);
        //分享说明
        intent.putExtra("shareExplain",shareExplain);
        ActivityUtils.getTopActivity().startActivity(intent);
    }


    public static class MyFile extends PansoftCloudUtil.CloudFile {

    }
}
